import base64
import os
import threading
import tkinter as tk
import tkinter.font as tk_font
import tkinter.messagebox as message_box
from pathlib import Path
from tkinter import StringVar, IntVar
from tkinter import scrolledtext, ttk
from tkinter.filedialog import askdirectory, askopenfilename
from typing import List

from icon import img
from merge_excel import merge_excel, get_excel_files


class App(tk.Frame):
    var_target_path: StringVar
    var_progress: IntVar
    ui_output_text: scrolledtext.ScrolledText
    excel_files: List[Path]
    out_file: Path

    def __init__(self, master=None):
        super().__init__(master)
        # 使用Frame增加一层容器
        self.master = master

        self.var_target_path = StringVar()
        self.var_template_file = StringVar()
        self.var_progress = IntVar()

        s = ttk.Style()
        s.configure(".", font_family="微软雅黑")
        s.configure("X.TButton", foreground="red")

        self.master.title("合并 Excel")

        self.create_widget_form()
        self.create_widget_output()
        self.create_widget_actions()

    def create_widget_form(self):

        ui_frame = tk.Frame(self.master)
        ui_label1 = ttk.Label(ui_frame, text="模板文件：")
        ui_template_path_entry = ttk.Entry(
            ui_frame, textvariable=self.var_template_file, width=50
        )
        ui_template_path_select_button = ttk.Button(
            ui_frame, text="选择模板", width=10, command=self.on_select_template_file
        )

        ui_label1.grid(row=0, column=0, padx=(0, 0))
        ui_template_path_entry.grid(row=0, column=1, sticky=tk.W)
        ui_template_path_select_button.grid(row=0, column=2, padx=5)

        ui_label2 = ttk.Label(ui_frame, text="目标路径：")
        ui_path_entry = ttk.Entry(ui_frame, textvariable=self.var_target_path, width=50)

        ui_label2.grid(row=1, column=0, padx=(0, 0))
        ui_path_entry.grid(row=1, column=1, sticky=tk.W)

        ui_path_select_button = ttk.Button(
            ui_frame, text="选择路径", width=10, command=self.on_select_path
        )
        ui_path_select_button.grid(row=1, column=2, padx=5)

        ui_label3 = ttk.Label(ui_frame, text="合并进度：")
        ui_label3.grid(row=2, column=0, sticky=tk.W)
        ui_progress = ttk.Progressbar(ui_frame, length=450, variable=self.var_progress)
        ui_progress.grid(row=2, column=1, columnspan=2, sticky=tk.E, pady=5)

        ui_frame.pack(pady=10)

    def create_widget_actions(self):
        ui_frame = tk.Frame(self.master)

        ui_pen_button = ttk.Button(
            ui_frame, text="打开输出文件", width=15, command=self.on_open_out_file
        )
        ui_pen_button.grid(row=0, column=1, padx=5)

        ui_merge_button = ttk.Button(
            ui_frame,
            text="合并",
            width=10,
            command=lambda: self.thread_it(self.on_merge_excel),
        )
        ui_merge_button.grid(row=0, column=0, sticky=tk.W, padx=5)

        ui_frame.pack(pady=10)

    def create_widget_output(self):
        ft = tk_font.Font(family="微软雅黑", size=10)
        self.ui_output_text = scrolledtext.ScrolledText(
            self.master, font=ft, padx=5, pady=5, borderwidth=1
        )
        self.ui_output_text.tag_config("strong", foreground="red")
        self.ui_output_text.pack(padx=5, pady=5)

    def on_insert_text(self, text, strong=None):
        self.ui_output_text.insert(tk.END, text)
        if strong is not None:
            self.ui_output_text.insert(tk.END, f"{strong}", "strong")
        self.ui_output_text.insert(tk.END, "\n")
        self.ui_output_text.see(tk.END)  # 自动滚动到末尾

    def on_select_path(self):
        path = askdirectory()
        self.var_target_path.set(path)
        excel_files = get_excel_files(path)
        self.excel_files = excel_files
        self.on_insert_text("-" * 40)
        self.on_insert_text(f"共{len(excel_files)}个文件")

    def on_select_template_file(self):
        file = askopenfilename()
        self.var_template_file.set(file)
        self.var_template_file.set(file)
        self.on_insert_text("=" * 40)
        self.on_insert_text(f"{file}")

    def on_callback(self, params):
        if isinstance(params, str):
            self.on_insert_text(params)
            return
        msg = params.get("msg")
        self.on_insert_text(msg)
        total = params.get("total")
        progress = params.get("progress")
        if total > 0:
            self.var_progress.set(100 * progress / total)

    def on_merge_excel(self):
        out_file = merge_excel(
            self.var_target_path.get(),
            template=self.var_template_file.get(),
            callback=self.on_callback,
        )
        ui_box = message_box.askokcancel("打开文件", "是否打开输出文件？")
        self.out_file = out_file
        if ui_box:
            os.startfile(out_file)

    def on_open_out_file(self):
        os.startfile(self.out_file)

    @staticmethod
    def thread_it(func, *args, **kwargs):
        t = threading.Thread(target=func, args=args, kwargs=kwargs)
        t.setDaemon(True)
        t.start()


if __name__ == "__main__":
    root = tk.Tk()

    tmp = open("tmp.ico", "wb+")
    tmp.write(base64.b64decode(img))
    tmp.close()
    root.iconbitmap("tmp.ico")
    os.remove("tmp.ico")

    app = App(root)
    app.mainloop()
